package com.yide.myworld.aspect;

import com.yide.myworld.annotation.InnerAuth;
import com.yide.myworld.constants.AuthConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 内部接口鉴权
 */
@Component
@Aspect
@Slf4j
public class InnerAuthAspect implements Ordered {

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint point, InnerAuth innerAuth) throws Throwable
    {
        String source = request.getHeader(AuthConstant.FROM_SOURCE);
        // 内部请求验证
        if (!StringUtils.equals(AuthConstant.INNER, source))
        {
            // business_error
            log.error("没有内部访问权限，不允许访问");
        }

        String userId = request.getHeader(AuthConstant.DETAILS_USER_ID);
        // 用户信息验证
        if (innerAuth.isUser() && StringUtils.isEmpty(userId) )
        {
            // business_error
            log.error("没有设置用户信息，不允许访问 ");
        }
        return point.proceed();
    }
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
